﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Core.Common.Monitor;
using Core.Expansion;
using Newtonsoft.Json.Linq;
using Tool.Common;
using Tool.Web.HttpHelper;
using static Core.Common.Global;

namespace Core.Monitors
{
	public class BiliDynamic : Tool.Common.Monitor
	{
		long num = 0L;

		public BiliDynamic(object flag) : base(flag)
		{
			ClearAllCloseEvent();
			ClearAllStartEvent();
			CloseEvent += () => CQ.Log($"关闭了对{flag}的动态监控任务");
			StartEvent += () => CQ.Log($"开启了对{flag}的动态监控任务");
		}

		protected override void Handle()
		{
			JObject jObject;
			int num2;
			try
			{
				jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?host_uid=" + flag)));
				num2 = jObject["data"]["cards"].Count();
			}
			catch (Exception ex)
			{
				CQ.Log($"本次uid为{flag}的动态无数据,错误信息为:{ex.Message}");
				return;
			}
			if (num == 0L)
			{
				num = jObject["data"]["cards"][0]["desc"]["timestamp"].ToObject<long>();
				return;
			}
			for (int i = 0; i < num2 && jObject["data"]["cards"][i]["desc"]["timestamp"].ToObject<long>() > num; i++)
			{
				MonitorInfo monitorInfo = DynamicInfo.Find((e) => e.flag == (string)flag);
				lock (monitorInfo)
				{
					string msg = DynamicParse(jObject["data"]["cards"][i]["card"].ToString());
					foreach (MonitorItem item in monitorInfo.item)
					{
						if (item.status == 1)
						{
							if (item.type == 0)
							{
								CQ.SendGroupMessage(item.num, msg);
							}
							if (item.type == 1)
							{
								CQ.SendPrivateMessage(item.num, msg);
							}
						}
						Thread.Sleep(1000);
					}
				}
				long num3 = jObject["data"]["cards"][0]["desc"]["timestamp"].ToObject<long>();
				if (num3 > num)
				{
					num = num3;
				}
			}
		}

		private static string DynamicParse(string dynamic)
		{
			JObject jObject = JObject.Parse(dynamic);
			if (jObject.ContainsKey("origin"))
			{
				return jObject["user"]["uname"]?.ToString() + ":\r\n" + jObject["item"]["content"]?.ToString() + "\r\n" + DynamicParse(jObject["origin"].ToString());
			}
			if (jObject.ContainsKey("episode_id"))
			{
				string text = ImagePath + TimeHelp.GetCurrentTimeUnix().ToString() + ".jpg";
				File.WriteAllBytes(text, HttpNet.Get(jObject["cover"].ToString()));
				text = text.HandleImage();
				return CQ.Code_Image(text.HandleImagePath()) + "\r\n" + jObject["apiSeasonInfo"]["title"]?.ToString() + "\r\n" + jObject["url"]?.ToString();
			}
			if (jObject.ContainsKey("schema"))
			{
				string text2 = ImagePath + TimeHelp.GetCurrentTimeUnix().ToString() + ".jpg";
				File.WriteAllBytes(text2, HttpNet.Get(jObject["cover"].ToString()));
				string str = jObject["upper"]?.ToString() + "\r\n";
				str = str + CQ.Code_Image(text2.HandleImagePath()) + "\r\n";
				str = str + jObject["title"]?.ToString() + "\r\n" + jObject["intro"]?.ToString() + "\r\n";
				return str + "https://www.bilibili.com/audio/au" + jObject["id"]?.ToString();
			}
			if (jObject.ContainsKey("sketch"))
			{
				string text3 = ImagePath + TimeHelp.GetCurrentTimeUnix().ToString() + ".jpg";
				File.WriteAllBytes(text3, HttpNet.Get(jObject["sketch"]["cover_url"].ToString()));
				return jObject["user"]["uname"]?.ToString() + ":\r\n" + jObject["vest"]["content"]?.ToString() + "\r\n" + CQ.Code_Image(text3.HandleImagePath()) + "\r\n" + jObject["sketch"]["title"]?.ToString() + "\r\n" + jObject["sketch"]["target_url"]?.ToString();
			}
			if (jObject.ContainsKey("id") && jObject.ContainsKey("title") && jObject.ContainsKey("summary"))
			{
				string text4 = ImagePath + TimeHelp.GetCurrentTimeUnix().ToString() + ".jpg";
				var url = jObject["banner_url"].ToString();
				if (string.IsNullOrWhiteSpace(url))
				{
					if (jObject["origin_image_urls"].Count() != 0)
					{
						url = jObject["origin_image_urls"][0].ToString();
					}
				}
				if (!string.IsNullOrWhiteSpace(url)) File.WriteAllBytes(text4, HttpNet.Get(url));
				return CQ.Code_Image(text4.HandleImagePath()) + "\r\n" + jObject["title"]?.ToString() + "\r\n" + jObject["summary"]?.ToString() + "......\r\nhttps://www.bilibili.com/read/cv" + jObject["id"]?.ToString();
			}
			if (jObject.ContainsKey("videos") && jObject["videos"].ToObject<int>() > 0)
			{
				string text5 = ImagePath + TimeHelp.GetCurrentTimeUnix().ToString() + ".jpg";
				File.WriteAllBytes(text5, HttpNet.Get(jObject["pic"].ToString()));
				return jObject["owner"]["name"]?.ToString() + ":\r\n" + jObject["dynamic"]?.ToString() + "\r\n" + CQ.Code_Image(text5.HandleImagePath()) + "\r\n" + jObject["title"]?.ToString() + "\r\nhttps://www.bilibili.com/video/av" + jObject["aid"]?.ToString();
			}
			if (jObject.ContainsKey("item"))
			{
				JObject jObject2 = (JObject)jObject["item"];
				JObject jObject3 = (JObject)jObject["user"];
				if (jObject2.ContainsKey("tags") && ((JArray)jObject2["tags"]).Count >= 1 && jObject2["tags"][0].ToString() == "小视频")
				{
					string str2 = jObject3["name"]?.ToString() + "发布了小视频:\r\n" + jObject2["description"]?.ToString() + "\r\n";
					string text6 = ImagePath + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
					File.WriteAllBytes(text6, HttpNet.Get(jObject2["cover"]["unclipped"].ToString()));
					text6 = text6.HandleImage();
					return str2 + CQ.Code_Image(text6.HandleImagePath()) + "\r\n播放地址:" + Url.GetShortUrl(jObject2["video_playurl"].ToString());
				}
				if (jObject2.ContainsKey("content") && jObject3.ContainsKey("uname"))
				{
					return jObject3["uname"]?.ToString() + ":\r\n" + jObject2["content"]?.ToString();
				}
				if (jObject2.ContainsKey("description"))
				{
					string text7 = jObject3["name"]?.ToString() + ":\r\n" + jObject2["description"]?.ToString();
					if (jObject2.ContainsKey("pictures"))
					{
						text7 += "\r\n";
						for (int i = 0; i < jObject2["pictures"].Count(); i++)
						{
							string text8 = ImagePath + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
							File.WriteAllBytes(text8, HttpNet.Get(jObject2["pictures"][i]["img_src"].ToString()));
							text8 = text8.HandleImage();
							text7 += CQ.Code_Image(text8.HandleImagePath());
						}
					}
					return text7;
				}
			}
			else if (jObject.ContainsKey("roomid") && jObject.ContainsKey("short_id"))
			{
				string str3 = jObject["uname"]?.ToString() + "\r\n的直播间\r\n" + jObject["title"]?.ToString() + "\r\n";
				string text9 = ImagePath + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
				File.WriteAllBytes(text9, HttpNet.Get(jObject["cover"].ToString()));
				return str3 + CQ.Code_Image(text9.HandleImagePath()) + "\r\nhttps://live.bilibili.com/" + jObject["roomid"]?.ToString();
			}
			return "解析失败，请反馈给开发者，以支持此类型动态的解析";
		}
	}
}
